package com.yqy.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yqy.entity.StudentGrade;
import com.yqy.mapper.StudentGradeMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author yiqianyi
 * @date 2022/3/23 9:35
 */
@CrossOrigin
@RestController
@Api(tags = {"学生成绩控制层"})
public class StudentGradeController {
  private static final Logger log = LoggerFactory.getLogger(StudentGradeController.class);
  @Autowired private StudentGradeMapper studentGradeMapper;

  @PostMapping("/student/grade/getPage")
  @ApiOperation(value = "分页获取学生成绩信息", notes = "/student/grade/getPage")
  public IPage<StudentGrade> getPageStudentInfo(
      @RequestParam @ApiParam(name = "pageNum", value = "pageNum", required = true) int pageNum,
      @RequestParam @ApiParam(name = "pageSize", value = "pageSzie", required = true) int pageSize,
      @RequestBody @ApiParam(name = "StudentGrade", value = "StudentGrade", required = true)
          StudentGrade studentGrade) {
    QueryWrapper queryWrapper = new QueryWrapper();
    if (!("").equals(studentGrade.getIsClass())) {
      queryWrapper.eq("isClass", studentGrade.getIsClass());
    }
    queryWrapper.orderByDesc("sum_score");
    Page<StudentGrade> studentGradePage = new Page<>(pageNum, pageSize);
    return studentGradeMapper.selectPage(studentGradePage, queryWrapper);
  }

  @PostMapping("/student/grade/export")
  @ApiOperation(value = "导出学生成绩信息 response", notes = "/student/grade/export")
  public void export(
      HttpServletResponse response,
      @RequestBody @ApiParam(name = "studentGrade", value = "studentGrade", required = true)
          StudentGrade studentGrade) {
    try {
      response.setHeader("content-Type", "application/vnd.ms-excel");
      response.setHeader("Content-Disposition", "attachment;filename=user.xls");
      ExportParams exportParams = new ExportParams();
      Workbook workbook =
          ExcelExportUtil.exportExcel(exportParams, StudentGrade.class, getData(studentGrade));
      workbook.write(response.getOutputStream());
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }

  private List<StudentGrade> getData(StudentGrade studentGrade) {
    QueryWrapper queryWrapper = new QueryWrapper();
    if (!("").equals(studentGrade.getUsername())) {
      queryWrapper.like("username", studentGrade.getUsername());
    }

    if (!("").equals(studentGrade.getIsClass())) {
      queryWrapper.like("isClass", studentGrade.getIsClass());
    }
    queryWrapper.orderByDesc("sum_score");
    return studentGradeMapper.selectList(queryWrapper);
  }

  @PostMapping("/student/grade/import")
  public String importExcel(@RequestParam("file") MultipartFile file) {
    ImportParams importParams = new ImportParams();
    importParams.setNeedVerfiy(false);
    try {
      ExcelImportResult<StudentGrade> result =
          ExcelImportUtil.importExcelMore(file.getInputStream(), StudentGrade.class, importParams);
      List<StudentGrade> studnetGradeList = result.getList();
      List<StudentGrade> studentGrades = studentGradeMapper.selectList(null);

      for (StudentGrade sgList : studnetGradeList) {
        for (StudentGrade sg : studentGrades) {
          if (sgList.getUsername().equals(sg.getUsername())) {
            sg.setWtQzScore(sgList.getWtQzScore());
            sg.setDyQzScore(sgList.getDyQzScore());
            sg.setZyQzScore(sgList.getZyQzScore());

            int ps = sg.getWtPsScore() + sg.getZyPsScore() + sg.getDyPsScore();
            int qz = sg.getWtQzScore() + sg.getZyQzScore() + sg.getDyQzScore();
            Double sum = ps * 0.3 + qz * 0.7;
            sg.setSumScore((double) (Math.round(sum * 100) / 100.0));
            studentGradeMapper.updateById(sg);
          }
        }
      }
      log.info("从Excel导入数据一共 {} 行 ", studnetGradeList.size());
    } catch (IOException e) {
      log.error("导入失败：{}", e.getMessage());
    } catch (Exception e1) {
      log.error("导入失败：{}", e1.getMessage());
    }
    return "导入成功";
  }
}
